package nayasis.common.xml;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.filter.Filters;
import org.jdom2.input.SAXBuilder;
import org.jdom2.xpath.XPathExpression;
import org.jdom2.xpath.XPathFactory;

public class XmlBuilder {
	
	private Document doc;

	/**
	 * 특정 XML 파일을 가져온다.
	 * 
	 * @param fileName XML 파일경로
	 * @throws IOException
	 * @throws JDOMException
	 */
	public XmlBuilder( String fileName ) throws IOException, JDOMException {

		SAXBuilder builder = new SAXBuilder();
		
		this.doc = builder.build( new File(fileName) );
		
	}

	public List<Element> getElements( String xPath ) {
		
		XPathExpression<Element> compile = XPathFactory.instance().compile( xPath, Filters.element() );
		
		return compile.evaluate( doc );
		
	}

	public Element getElement( String xPath ) {
		
		XPathExpression<Element> compile = XPathFactory.instance().compile( xPath, Filters.element() );
		
		return compile.evaluateFirst( doc );
		
	}
	
	public List<Attribute> getAttributes( String xPath ) {
		
		XPathExpression<Attribute> compile = XPathFactory.instance().compile( xPath, Filters.attribute() );
		
		return compile.evaluate( doc );
		
	}

	public Attribute getAttribute( String xPath ) {
		
		XPathExpression<Attribute> compile = XPathFactory.instance().compile( xPath, Filters.attribute() );
		
		return compile.evaluateFirst( doc );
		
	}
	
	public String getValue( Element element ) {

		if( element == null ) {
			return null;
		} else {
			return element.getValue();
		}
		
	}

	public String getValue( Attribute attribute ) {

		if( attribute == null ) {
			return null;
		} else {
			return attribute.getValue();
		}
		
	}

	public String getElementValue( String xPath ) {
		
		return getValue( getElement(xPath) );
		
	}
	
	
	public String getAttributeValue( String xPath ) {

		return getValue( getAttribute(xPath) );
	
	}
	

	
}
